package com.zzy.mccjt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzy.mccjt.utils.ServerEncoderUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: mccjt-cloud
 * @description: websocket
 * 测试过程：
 * 1.打开两种不同类型的浏览器，分别打开http://www.websocket-test.com/
 * 2.输入ws://127.0.0.1:3080/websocket/tunnel  点击连接
 * 3.发送消息{"name":"001","toUserId":1}    toUserId是需要发送的用户的id，id=登录顺序
 *
 *
 * @author: zhouyang.zheng
 * @create: 2022-08-01 11:10
 **/
@ServerEndpoint(value = "/websocket/tunnel",encoders = {ServerEncoderUtils.class})
@Component
@Slf4j
public class WebSocketService {

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketService> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId = "";

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {
        log.info("客户端：{}连接成功", session.getId());
        this.session = session;
        this.userId = session.getId();
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //加入set中
            webSocketMap.put(userId,this);
        }else{
            //加入set中
            webSocketMap.put(userId,this);
            //在线数加1
            addOnlineCount();
        }
        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
        sendMessage("连接成功");
    }

    @OnMessage
    public void OnMessage(String msg, Session session) {
        log.info("客户端：{}收到消息：{}", session.getId(), msg);
        //可以群发消息
        //消息保存到数据库、redis
        if(!StringUtils.isEmpty(msg)){
            try {
                //解析发送的报文
                JSONObject jsonObject = JSON.parseObject(msg);
                //追加发送人(防止串改)
                jsonObject.put("fromUserId",this.userId);
                String toUserId=jsonObject.getString("toUserId");
                //传送给对应toUserId用户的websocket
                if(!StringUtils.isEmpty(toUserId) && webSocketMap.containsKey(toUserId)){
                    //业务
                    //sendInfo(msg, "1");
                    sendAllMessage(msg);
                }else{
                    //userId不存在
                    log.error("请求的userId:"+toUserId+"不在该服务器上");
                    webSocketMap.get(this.userId).sendMessage("请求的userId:"+toUserId+"不在该服务器上");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @OnClose
    public void OnClose(Session session, CloseReason closeReason) {
        log.info("客户端：{}连接断开", session.getId());
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            //从set中删除
            subOnlineCount();
        }
        log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        log.info("客户端：{}发生异常", session.getId());
    }

    /**
     * 发送单个消息
     * @param message
     */
    public void sendMessage(String message) {
        try {
            log.info("--------------websocket主动推送数据：{}",message);
            synchronized(session){
                this.session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送全员消息
     * @param message
     */
    public void sendAllMessage(String message) {
        try {
            log.info("--------------websocket主动推送数据：{}",message);
            synchronized(session){
                this.session.getAsyncRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendObjectMessage(Object message) {
        try {
            this.session.getBasicRemote().sendText(message.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //推送给指定用户
    public static void sendInfo(String message, String userId) {
        log.info("发送消息到:"+userId+"，报文:"+message);
        if(!StringUtils.isEmpty(userId) && webSocketMap.containsKey(userId)){
            webSocketMap.get(userId).sendMessage(message);
        }else{
            log.error("用户"+userId+",不在线！");
        }
    }

    /**
     * 获得此时的在线人数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 在线人数加1
     */
    public static synchronized void addOnlineCount() {
        WebSocketService.onlineCount++;
    }

    /**
     * 在线人数减1
     */
    public static synchronized void subOnlineCount() {
        WebSocketService.onlineCount--;
    }
}
